package com.shop.controller;

import cn.hutool.jwt.JWTUtil;
import com.shop.dto.MemberDto;
import com.shop.dto.MemberInfoDto;
import com.shop.dto.MemberLoginDto;
import com.shop.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wzby
 * @date 2022-12-02 13:24:15
 */
@RestController
@RequestMapping("/member-api/member")

public class MemberController {

    @Value("${beiyou.token.secret}")
    private  String TOKEN_SECRET ;

    @Autowired
    private MemberService memberService;

    @PostMapping("/login")
    public MemberInfoDto select(@RequestBody MemberLoginDto dto) throws Exception {

        MemberInfoDto memberInfoDto = memberService.login(dto);
        // 生成token
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("memberId", memberInfoDto.getId());
        map.put("phone",memberInfoDto.getPhone() );
        //令牌存在时间
        map.put("expire_time", System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 15);

        String token = JWTUtil.createToken(map, TOKEN_SECRET.getBytes());
        memberInfoDto.setToken(token);

        return memberInfoDto;
    }

    @PostMapping("/register")
    public Integer register(@RequestBody MemberDto dto) throws Exception {
        return memberService.register(dto);
    }

    @GetMapping("/vcode")
    public Integer sendVCode(@RequestParam String email) {
        return memberService.sendVCode(email);
    }


    @PutMapping
    public Integer update(@RequestBody MemberDto dto) {
        return memberService.update(dto);
    }

    @DeleteMapping("/{id}")
    public Integer delete(@PathVariable Integer id) {
        return memberService.delete(id);
    }
}
